package com.iotechn.uninotify.util;

import me.chanjar.weixin.common.util.crypto.PKCS7Encoder;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/12/26
 * Time: 22:01
 */
public class WxMpSignUtil {

//    public static void main(String arg[]) {
//        System.out.println(decrypt("GC4AoztsZYY8Fe3T4ODpeiczjoIt2I0mlFsO0DrTWXV", "ZIexXFxoZrr9909Ju2lndZTTwcgvBtR/0Lfk51OvXxbYdIu9BDzNg97zn+j3vH0O5wQP8U49yGoPH6/n7jgvoMKZflt15SiAVlsFAwxaNimg6Pt/ICL6jkkOMIusDB80yPadJrQGC5X+6W73S2qMBj+dllneO3cWQ4I+gSu0iEpUTZ5lGVgmR4unfiSR256qD9eRK2pYrnt0RzySPPIj1iPHtqnhEsVP5QDCOws5xcSS9aO1Dic9kdnzTpEArbUx6wcxgybTlQmQpwkJKID6bLm4TFFezf8chyB532JPR2U8MnDS63VrHXB6Uw1zMV6Mc4q8OHAwkxccOn4kp0aj+0iGfhIl8dnhJLTKJbQ1SoWVcT2QR59XQgjcnLTDvwUXA/aUCigdnYVpwg30ddODuqwdB2tH22gsX7FfGMlefCMqh7/zwhUftPjd1646qVepZUCttVmyjZ0NTJE4e8kPaaHJQkTG5AQyVvy7OR50kBu8jeOAoHYjUZoCPw+Bh/tM+1mKmmKG0GRC928YZK2dhPWx5vbgPTT38fhlbjmgPVHaDJaJn4yZyA9/N3ddu/DCfzaAFr5MJm62mt3hMCy93gy3Q51LsqmxqCohbXb/a7mAmIrg+w6S0wmZF4AU9hTr"));
//    }

    public static String decrypt(String encodingAesKey, String cipherText) {
        byte[] aseKey = Base64.decodeBase64(encodingAesKey + "=");
        byte[] original;
        byte[] networkOrder;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aseKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aseKey, 0, 16));
            cipher.init(2, keySpec, iv);
            networkOrder = Base64.decodeBase64(cipherText);
            original = cipher.doFinal(networkOrder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            byte[] bytes = PKCS7Encoder.decode(original);
            networkOrder = Arrays.copyOfRange(bytes, 16, 20);
            int xmlLength = bytesNetworkOrder2Number(networkOrder);
            String xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), "utf-8");
            new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), "utf-8");
            return xmlContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
        int sourceNumber = 0;
        for(int i = 0; i < 4; ++i) {
            sourceNumber <<= 8;
            sourceNumber |= bytesInNetworkOrder[i] & 255;
        }
        return sourceNumber;
    }

}
